/**
 * calculate and return location in latitude and longitude
 */
package com.google.zxing.client.android;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

/**
 * @author aabramov
 * 
 */

public final class LocatioManager implements LocationListener {

	private static final String TAG = LocatioManager.class.getSimpleName();
	double latitude = 0, longitude = 0;
	Context cont;

	private final Activity activity;
	private String rezultLocation = "";

	public LocatioManager(Activity activity) {
		this.activity = activity;
		checkLocation();

	}

	// Warning
	// Binding method to calculate the position
	public void checkLocation() {
		Context c = activity.getApplicationContext();

		LocationManager loc = (LocationManager) c
				.getSystemService(Context.LOCATION_SERVICE);
		Criteria cr = new Criteria();
		String provider = loc.getBestProvider(cr, true);
		loc.requestLocationUpdates(provider, 2000, 1, this);
		Location best;

		if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {

			best = loc.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		} else if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {

			best = loc.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		} else {

			best = loc.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
		}

		if (best != null) {
			setLatitude(best.getLatitude());
			setLongitude(best.getLongitude());

		}

	}

	// Return executed result string
	public String buildResult() {
		String lalitude = "" + getLatitude();
		String longitude = "" + getLongitude();

		rezultLocation = "";
		if (lalitude != null && longitude != null && lalitude.length() > 0
				&& longitude.length() > 0) {
			rezultLocation += "?lat=" + lalitude + "&lng=" + longitude;
		}
		return rezultLocation;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	public double getLatitude() {
		return latitude;
	}

	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}

	public double getLongitude() {
		return longitude;
	}

	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	public String getRezultLocation() {
		return rezultLocation;
	}

}
